In [ ]:
### Packages
import cv2
import numpy as np
### 전역 변수 초기화
drawing = False # 드래그 상태를 확인하기 위한 플래그
ix, iy = -1, -1 # 드래그 시작 지점
ex, ey = -1, -1 # 드래그 끝 지점
### 마우스 콜백 함수
def fn_draw_rectangle(event, x, y, flags, param):
global ix, iy, ex, ey, drawing, img_out, temp_img
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing:
temp_img = img_out.copy()
cv2.rectangle(temp_img, (ix, iy), (x, y), (0, 255, 0), 2)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
ex, ey = x, y
if ix > ex: ix, ex = ex, ix
if iy > ey: iy, ey = ey, iy
### 모자이크 처리
if (ex-ix>10) & (ey-iy>10):
roi = img_out[iy:ey, ix:ex]
roi = cv2.resize(roi, (10, 10), interpolation=cv2.INTER_LINEAR)
roi = cv2.resize(roi, (ex-ix, ey-iy), interpolation=cv2.INTER_NEAREST)
img_out[iy:ey, ix:ex] = roi
temp_img = img_out.copy()
### 이미지 불러오기
img_path = r"D:\image\lena.png"
img_raw = cv2.imread(img_path)
img_out = img_raw.copy()
temp_img = img_out.copy()
while True:
cv2.imshow('image', temp_img)
key = cv2.waitKey(1) & 0xFF
if key == ord("m"):
cv2.setMouseCallback('image', fn_draw_rectangle)
if key == ord("o"):
img_out = img_raw.copy()
temp_img = img_raw.copy()
if key == ord("q"):
break
cv2.destroyAllWindows()